// 定义开发路径
let devUrl = "./src"
//通过解构赋值 引入gulp API
let {src , dest , watch , series , parallel} = require('gulp');
//1.引入sass
let sass = require('gulp-sass');
sass.compiler = require('node-sass');
//2.引入autoprefixer
let autoprefixer = require('gulp-autoprefixer');
//3.引入browserSync
let browserSync = require('browser-sync').create();
//使用变量引用 reload 方法
let reload = browserSync.reload;
// 4.引用babel转js,压缩工具
let babel = require('gulp-babel');
let uglify = require('gulp-uglify');
//压缩图片
let imagemin = require('gulp-imagemin');

//开发环境将sass编译成css
function devSass() {
  return src( devUrl + '/scss/**/*.scss')
    .pipe(sass().on('error', sass.logError))
	.pipe(autoprefixer({
		//是否美化样式
		cascade: true
	 }))
    .pipe(dest(devUrl + '/css'));
}

//压缩图片
function minImg(){
	return src(devUrl + '/images/**/*.*')
        .pipe(imagemin())
        .pipe(dest('dist/images'))
}

//打包压缩css代码
function minCss(){
	return src( devUrl + '/css/**/*.css')
	.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(dest('dist/css/'));
}

//转es5并压缩js
function minJS(){
	return src( devUrl + '/js/**/*.js')
				.pipe(babel({
					presets: ['@babel/env']
				}))
				.pipe(uglify({
					//是否忽略console.
					compress:{
						drop_console:true
					}
				}))
				.pipe(dest('dist/js/'));
}

// 开启静态服务器
function browser() {
    browserSync.init({
        server: {
			//对应监听的根目录
            baseDir: devUrl,
        },
		// 修改端口号
		port: (Math.random()*9999)+1000
    });
	watch(devUrl + '/css/**/*.css').on("change",reload)
	watch(devUrl + '/js/**/*.js').on("change",reload)
	watch(devUrl + '/*.html').on("change",reload)
	//监听目录,调用对应任务
	watch(devUrl + '/scss/**/*.scss',devSass)
};

// 定义一个copy任务
async function copyTask(){
	// 复制html font
	src(devUrl + '/*.html').pipe(dest('dist/'));
	src(devUrl + '/font/*').pipe(dest('dist/font/'));
};
exports.copyTask = copyTask;

//输出sass任务
exports.devSass = devSass;

//输出开发任务
exports.dev = browser;

// 定义打包任务
exports.build = series(devSass,minCss,minJS,minImg,copyTask);